//
//  LNHSelectGoodsParametersPopView.m
//  LNH
//
//  Created by cruise on 2018/2/8.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "LNHSelectGoodsParametersPopView.h"

#import "LNHGoodsParametersPopCell.h"

#import "LNHGoodsDetailViewModel.h"

#import <TTGTagCollectionView/TTGTextTagCollectionView.h>

#import "LNHStepperView.h"

#import "CAAddShopCartApi.h"

#import "LNHConfirmOrderViewController.h"

@interface LNHSelectGoodsParametersPopView() <UITableViewDelegate, UITableViewDataSource> {
    UIView *_rootView;
}

@property (nonatomic, strong) UIView *coverView;
@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *priceLabel;
@property (nonatomic, strong) UILabel *stockLabel;
@property (nonatomic, strong) UILabel *selectedContentLabel;

@property (nonatomic, strong) UIButton *shopcarBtn;
@property (nonatomic, strong) UIButton *buyBtn;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) LNHStepperView *footerView;

@property (nonatomic, strong) LNHGoodsDetailViewModel *viewModel;

@end

@implementation LNHSelectGoodsParametersPopView

/**
 为视图绑定 viewModel
 
 @param viewModel 要绑定的ViewModel
 @param params 额外参数
 */
- (void)bindViewModel:(id <LMViewProtocol>)viewModel withParams:(NSDictionary *)params{
    if ([viewModel isKindOfClass:[LNHGoodsDetailViewModel class]]){
        
        self.viewModel = (LNHGoodsDetailViewModel *)viewModel;
        
        [[RACObserve(self.viewModel, infoDict) filter:^BOOL(id  _Nullable value) {
            return value != nil;
        }] subscribeNext:^(NSDictionary *dict) {
            
            [self.imageView sd_setImageWithURL:[NSURL URLWithString:dict[kPropertyDataKeyGoodsDetailGoodsUrl]]];
//            [self.priceLabel setText:dict[kPropertyDataKeyGoodsDetailPrice]];
//            [self.stockLabel setText:dict[kPropertyDataKeyGoodsDetailStock]];
//            [self.selectedContentLabel setText:@"请选择"];
            
        }];
        
        RAC(self.priceLabel, text) = RACObserve(self.viewModel, priceStr);
        RAC(self.stockLabel, text) = RACObserve(self.viewModel, stockStr);
        
        [[RACObserve(self.viewModel, parameterList) filter:^BOOL(NSArray *list) {
            return list.count > 0;
        }] subscribeNext:^(NSArray *list) {
            
            [self layoutIfNeeded];
            
            [self.tableView reloadData];
            
        }];
        
        [RACObserve(self.viewModel, stock) subscribeNext:^(id  _Nullable x) {
            if ([x integerValue] == 1) {
                [self.footerView.stepper.incrementButton setTitleColor:RGBACOLOR(172, 172, 172,1) forState:UIControlStateNormal];
            }
            
            self.footerView.stepper.valueChangedCallback = ^(PKYStepper * stepper,float count) {
                
                if (count > 1) {
                    [stepper.decrementButton setTitleColor:RGBACOLOR(238, 128, 16,1) forState:UIControlStateNormal];
                } else {
                    [stepper.decrementButton setTitleColor:RGBACOLOR(172, 172, 172,1) forState:UIControlStateNormal];
                }
                
                if ((int)count == [x intValue]) {
                    [stepper.incrementButton setTitleColor:RGBACOLOR(172, 172, 172,1) forState:UIControlStateNormal];
                } else {
                    [stepper.incrementButton setTitleColor:RGBACOLOR(238, 128, 16,1) forState:UIControlStateNormal];
                }
                
                stepper.countLabel.text = [NSString stringWithFormat:@"%@",@(count)];
            };
        }];
        
        RAC(self.footerView.stepper, maximum) = RACObserve(self.viewModel, stock);
        
    }
    
}

/**
 初始化额外数据
 */
- (void)lm_initializeForView{
    
}

/**
 初始化视图
 */
- (void)lm_createViewForView{
    
    [self setFrame:(CGRect){ 0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT*0.7 }];
    
    [self addSubview:self.contentView];
    
    [self.contentView addSubview:self.imageView];
    [self.contentView addSubview:self.priceLabel];
    [self.contentView addSubview:self.stockLabel];
    [self.contentView addSubview:self.selectedContentLabel];
    
    [self.contentView addSubview:self.shopcarBtn];
    [self.contentView addSubview:self.buyBtn];
    [self.contentView addSubview:self.tableView];
    
    [self setNeedsUpdateConstraints];
}

-(void) updateConstraints {
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 80));
        make.top.equalTo(self.contentView).offset(10);
        make.left.equalTo(self.contentView).offset(15);
    }];
    
    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imageView.mas_top).offset(15);
        make.left.equalTo(self.imageView.mas_right).offset(20);
        make.right.equalTo(self.contentView.mas_right).offset(-20);
        make.height.mas_equalTo(20);
    }];
    
    [self.stockLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.priceLabel.mas_bottom);
        make.left.right.equalTo(self.priceLabel);
        make.height.mas_equalTo(20);
    }];
    
    [self.selectedContentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.stockLabel.mas_bottom);
        make.left.right.equalTo(self.priceLabel);
        make.height.mas_equalTo(20);
    }];
    
    if (self.viewModel.isUpgrade) {
        [self.buyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.contentView.mas_bottom).offset(isIPhoneX ? -34: 0);
            make.left.and.right.equalTo(self.contentView);
            make.height.mas_equalTo(40);
        }];
    } else {
        [self.shopcarBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.contentView.mas_bottom).offset(isIPhoneX ? -34: 0);
            make.left.equalTo(self.contentView.mas_left);
            make.right.equalTo(self.buyBtn.mas_left);
            make.height.mas_equalTo(40);
            make.width.equalTo(self.buyBtn);
        }];
        
        [self.buyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.shopcarBtn);
            make.left.equalTo(self.shopcarBtn.mas_right);
            make.right.equalTo(self.contentView.mas_right);
            make.height.mas_equalTo(40);
            make.width.equalTo(self.shopcarBtn);
        }];
    }
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imageView.mas_bottom).offset(10);
        make.bottom.equalTo(self.shopcarBtn.mas_top);
        make.left.right.equalTo(self.contentView);
    }];
    
    [super updateConstraints];
}

#pragma mark - getter

-(UIView *) coverView {
    if (!_coverView) {
        _coverView = [[UIView alloc] initWithFrame:[[UIApplication sharedApplication] keyWindow].bounds];
        [_coverView setBackgroundColor:RGBACOLOR(0, 0, 0, 0.7)];
        _coverView.alpha = 0;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [[tap rac_gestureSignal] subscribeNext:^(id x) {
            [self hideView];
        }];
        [_coverView addGestureRecognizer:tap];
    }
    return _coverView;
}

-(UIView *) contentView {
    if (!_contentView) {
        _contentView = [UIView new];
        [_contentView setBackgroundColor:[UIColor whiteColor]];
        
    }
    return _contentView;
}

-(UIImageView *) imageView {
    if (!_imageView) {
        _imageView = [UIImageView new];
        [_imageView setContentMode:UIViewContentModeScaleAspectFit];
        [_imageView.layer setBorderWidth:ONE_PIXEL];
        [_imageView.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    }
    return _imageView;
}

-(UILabel *) priceLabel {
    if (!_priceLabel) {
        _priceLabel = [UILabel new];
        [_priceLabel setTextColor:RGBCOLOR(241, 90, 36)];
        [_priceLabel setFont:[UIFont systemFontOfSize:14]];
    }
    return _priceLabel;
}

-(UILabel *) stockLabel {
    if (!_stockLabel) {
        _stockLabel = [UILabel new];
        [_stockLabel setTextColor:RGBCOLOR(77, 77, 77)];
        [_stockLabel setFont:[UIFont systemFontOfSize:14]];
    }
    return _stockLabel;
}

-(UILabel *) selectedContentLabel {
    if (!_selectedContentLabel) {
        _selectedContentLabel = [UILabel new];
        [_selectedContentLabel setTextColor:RGBCOLOR(77, 77, 77)];
        [_selectedContentLabel setFont:[UIFont systemFontOfSize:14]];
    }
    return _selectedContentLabel;
}

-(UIButton *) shopcarBtn {
    if (!_shopcarBtn) {
        _shopcarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_shopcarBtn setBackgroundColor:RGBCOLOR(245, 171, 51)];
        [_shopcarBtn setTitle:@"加入购物车" forState:UIControlStateNormal];
        [_shopcarBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [_shopcarBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

        [[_shopcarBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            NSString *number = self.footerView.stepper.countLabel.text;
            NSString *skuStr = @"";
            if (self.viewModel.skuAttrList.count > 0) {
                NSString *skuId = [self.viewModel.selectSkuList componentsJoinedByString:@"-"];
                NSLog(@"%@", self.viewModel.skuDict[skuId][@"id"]);
                skuStr = [NSString stringWithFormat:@"%ld", [self.viewModel.skuDict[skuId][@"id"] integerValue]];
            }
            CAAddShopCartApi *addShopCartApi = [[CAAddShopCartApi alloc] initWithGoodsId:self.viewModel.infoDict[@"kPropertyListDataKeyID"] Number:number skuId:skuStr];
            [MBProgressHUD showHUDAddedTo:self animated:YES];
            [addShopCartApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                [MBProgressHUD hideHUDForView:self animated:YES];
                CAAddShopCartApi *api = (CAAddShopCartApi *) request;
                if (api.done) {
                    [SVProgressHUD lm_displaySuccessWithStatus:@"商品已添加到购物车"];
                    [self hideView];
                } else {
                    [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
                }
            } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                [MBProgressHUD hideHUDForView:self animated:YES];
                [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
            }];
            
        }];
    }
    return _shopcarBtn;
}

-(UIButton *) buyBtn {
    if (!_buyBtn) {
        _buyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_buyBtn setBackgroundColor:RGBCOLOR(237, 119, 66)];
        [_buyBtn setTitle:@"立即购买" forState:UIControlStateNormal];
        [_buyBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [_buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [[_buyBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            NSString *number = self.footerView.stepper.countLabel.text;
            NSString *skuStr = @"";
            NSString *levelId = self.viewModel.levelId == nil ? @"" : self.viewModel.levelId;
            if (self.viewModel.skuAttrList.count > 0) {
                NSString *skuId = [self.viewModel.selectSkuList componentsJoinedByString:@"-"];
                NSLog(@"%@", self.viewModel.skuDict[skuId][@"id"]);
                skuStr = [NSString stringWithFormat:@"%ld", [self.viewModel.skuDict[skuId][@"id"] integerValue]];
            }
            NSString *router = [JLRoutes lm_generateURLWithPattern:LMNavPushRoute parameters:@[NSStringFromClass(LNHConfirmOrderViewController.class)] extraParameters:@{@"goodsId":self.viewModel.infoDict[@"kPropertyListDataKeyID"],@"sku":skuStr,@"number":number,@"level":levelId,@"inviteCode":self.params[@"inviteCode"] == nil ? @"":self.params[@"inviteCode"]}];
            [[RACScheduler mainThreadScheduler] schedule:^{
                
                [[UIApplication sharedApplication] openURL:JLRGenRouteURL(LMDefaultRouteSchema, router) options:nil completionHandler:nil];
                
            }];
            [self hideView];
        }];
    }
    return _buyBtn;
}

-(UITableView *) tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [_tableView setDataSource:self];
        [_tableView setDelegate:self];
        [_tableView setTableFooterView:self.footerView];
        
        [_tableView setRowHeight:UITableViewAutomaticDimension];
        [_tableView setEstimatedRowHeight:80];
        _tableView.userInteractionEnabled = YES;
    }
    return _tableView;
}

-(LNHStepperView *) footerView {
    if (!_footerView) {
        _footerView = [[LNHStepperView alloc] initWithFrame:(CGRect){ 0, 0, SCREEN_WIDTH, 80 }];
        _footerView.userInteractionEnabled = YES;
//        UITapGestureRecognizer *gesture = [UITapGestureRecognizer new];
//        [self.footerView addGestureRecognizer:gesture];
//        [[gesture rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
//            NSLog(@"1123123123");
//        }];
    }
    return _footerView;
}

#pragma - mark public

-(void) showView{
    _rootView = [[UIApplication sharedApplication] keyWindow].rootViewController.view;
    [_rootView addSubview:self.coverView];
    
    [[UIApplication sharedApplication].windows[0] addSubview:self];
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10,10)];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
    
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        [self.coverView setAlpha:0.6f];
        
        [self setFrame:(CGRect){ 0, SCREEN_HEIGHT-SCREEN_HEIGHT*0.7, SCREEN_WIDTH, SCREEN_HEIGHT*0.7 }];
        
    } completion:nil];
}

-(void) hideView {
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        [self.coverView setAlpha:0.f];
        [self setFrame:(CGRect){ 0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT*0.7 }];
        
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma - mark UITableViewDelegate & UITableViewDataSource

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.viewModel.parameterList.count;
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LNHGoodsParametersPopCell *cell = [tableView dequeueReusableCellWithIdentifier:GCN(LNHGoodsParametersPopCell)];
    
    if (cell == nil) {
        cell = [[LNHGoodsParametersPopCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:GCN(LNHGoodsParametersPopCell)];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    [cell configureForModel:self.viewModel selectedRow:indexPath.row];
    
    return cell;
}

@end
